package com.cmii.sjw.department.control.jsc.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.cmii.sjw.department.control.common.RedisService;
import com.cmii.sjw.department.control.jsc.model.entity.Menu;
import com.cmii.sjw.department.control.jsc.model.vo.MenuNode;
import com.cmii.sjw.department.control.jsc.service.UserRoleService;
import com.cmii.sjw.department.control.jsc.util.MenuTreeUtil;
import com.cmii.sjw.department.control.jsc.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试
 * @Author jfh
 * @Date 2024-11-12 周二 9:39
 * @Version 1.0
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/test")
public class TestController {

    @Resource
    private UserRoleService userRoleService;

    @Autowired
    private RedisService redisService;

    //清楚缓存
    @PostMapping("/clearCache")
    public Result clearCache(String key) {
        return redisService.delete(key) ? Result.success() : Result.error("清除缓存失败");
    }

    @PostMapping("/test")
    public Result test(String userId) {
        if(userId.equals("2")){
            throw new RuntimeException("测试异常");
        }
        StpUtil.login(userId);
//        StpUtil.login(103);
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return Result.success(tokenInfo);
    }

    @PostMapping("/test1")
    public Result test1() {
        Map<String, Object> result = new HashMap<>();
        long userId = StpUtil.getLoginIdAsLong();
        // 获取用户的所有菜单
        List<Menu> menus = userRoleService.getMenusByUserId(userId);
        List<MenuNode> menuTree = MenuTreeUtil.buildTree(menus);

        result.put("menu",menuTree);
        return Result.success(result);
    }

    @PostMapping("logout")
    public Result logout() {
        StpUtil.logout();
        return Result.success();
    }

    public static void main(String[] args) {
        String your_client_id = "6977931dceda415589eed856d066640a";
        String your_client_secret = "a0b61461f92742e7aaca75d83c1c3817";


        String authorization = "Basic " + Base64.encode(your_client_id + ":" + your_client_secret);
        System.out.println("authorization=" + authorization);
        System.out.println("sessionId=" + IdUtil.fastSimpleUUID());
    }
}
